package cqrtplm.aop;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hustcad.plm.pdm.flowbusiness.model.entity.WorkFlowObjectPackage;
import com.hustcad.plm.pdm.user.model.dto.PdmUserDTO;
import com.hustcad.plm.pdm.user.service.TyplmPrincipalService;
import com.hustcad.plm.pdm.user.service.organization.PdmUserService;
import com.hustcad.plm.pdm.workflow.model.entity.UserTaskDTO;
import com.hustcad.plm.pdm.workflow.model.vo.OptionalParticipantUserTaskVO;
import com.ty.basic.constant.TableTypeConstrant;
import com.ty.basic.entity.PrincipalEntity;
import cqrtplm.entity.DeptRoleDO;
import cqrtplm.mapper.DeptRoleMapper;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Aspect
@Component
@Slf4j
public class RTExecutorEchoAOP {

    @Resource
    private TyplmPrincipalService typlmPrincipalService;
    @Resource
    private DeptRoleMapper deptRoleMapper;
    @Resource
    private PdmUserService pdmUserService;


    @Around("execution(* com.hustcad.plm.pdm.flowbusiness.service.impl.TyplmFlowObjectPackageServiceImpl.checkWorkFlowStartRulesCommon(..))")
    public Object checkWorkFlowStartRulesCommon(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        Object result = proceedingJoinPoint.proceed();
        if (result instanceof WorkFlowObjectPackage) {
            WorkFlowObjectPackage pkg = (WorkFlowObjectPackage) result;
            enrichUserTaskWithDeptLeaders(pkg.getUserTaskList());
        }
        return result;
    }

    @Around("execution(* com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService.getOptionalParticipantUserTaskVO(..))")
    @SneakyThrows
    public Object getOptionalParticipantUserTaskVO(ProceedingJoinPoint proceedingJoinPoint) {
        Object result = proceedingJoinPoint.proceed();
        if (result instanceof OptionalParticipantUserTaskVO) {
            OptionalParticipantUserTaskVO vo = (OptionalParticipantUserTaskVO) result;
            enrichUserTaskWithDeptLeaders(vo.getUserTaskDTOS());
        }
        return result;
    }


    /**
     * 公共处理逻辑：根据第一个用户的组织结构，填充指定岗位的审批人
     */
    private void enrichUserTaskWithDeptLeaders(List<UserTaskDTO> userTaskList) {
        if (CollUtil.isEmpty(userTaskList))
            return;
        List<PdmUserDTO> firstUserList = userTaskList.get(0).getUserList();
        if (CollUtil.isEmpty(firstUserList))
            return;
        PdmUserDTO pdmUserDTO = firstUserList.get(0);
        BigInteger userId = new BigInteger(pdmUserDTO.getOid());
        // 获取上级组织（部门）
        List<PrincipalEntity> outParent = typlmPrincipalService.getOneOutParentOrg(
                new PrincipalEntity(userId, TableTypeConstrant.TY_USER_OTYPE)
        );
        if (CollUtil.isEmpty(outParent))
            return;
        List<String> deptIds = outParent.stream()
                .map(principal -> String.valueOf(principal.getOid()))
                .collect(Collectors.toList());
        // 查询该部门所有角色人员
        List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectDeptRoleDOListByDeptId(deptIds);
        Map<String, DeptRoleDO> roleIdToDeptRoleMap = deptRoleDOS.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toMap(
                        DeptRoleDO::getRoleName,
                        Function.identity(),
                        (existing, replacement) -> existing // 保留首个
                ));
        Map<String, String> map = new HashMap<>();
        map.put("发起者部门主管", "部门主管");
        map.put("发起者部长", "部长");
        map.put("发起者部门分管领导", "部门分管领导");
        // 收集需要查询的用户 ID（去重）
        Set<BigInteger> userIdsToQuery = new HashSet<>();
        for (UserTaskDTO task : userTaskList) {
            String taskName = task.getName();
            String roleName = map.get(taskName);
            if (roleName != null) {
                DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get(roleName);
                if (deptRoleDO != null && StringUtils.isNotBlank(deptRoleDO.getUserId())) {
                    userIdsToQuery.add(new BigInteger(deptRoleDO.getUserId()));
                }
            }
        }
        // 批量查询用户信息
        if (userIdsToQuery.isEmpty())
            return;
        List<PdmUserDTO> allUsers = pdmUserService.getUserListByIds(
                new ArrayList<>(userIdsToQuery)
        );
        Map<BigInteger, PdmUserDTO> userMap = allUsers.stream()
                .collect(Collectors.toMap(u -> new BigInteger(u.getOid()), Function.identity()));
        // 回填到对应的任务节点
        for (UserTaskDTO task : userTaskList) {
            String taskName = task.getName();
            String roleName = map.get(taskName);
            if (roleName != null) {
                DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get(roleName);
                if (deptRoleDO != null && StringUtils.isNotBlank(deptRoleDO.getUserId())) {
                    BigInteger targetUserId = new BigInteger(deptRoleDO.getUserId());
                    PdmUserDTO user = userMap.get(targetUserId);
                    if (user != null) {
                        task.setUserList(Collections.singletonList(user));
                    }
                }
            }
        }
    }

//    @Around("execution(* com.hustcad.plm.pdm.flowbusiness.service.impl.TyplmFlowObjectPackageServiceImpl.checkWorkFlowStartRulesCommon(com.hustcad.plm.pdm.workflow.model.entity.WorkFlowContainerObject))")
//    public Object checkWorkFlowStartRulesCommon(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
//        Object result = proceedingJoinPoint.proceed();
//        if(result instanceof WorkFlowObjectPackage){
//            WorkFlowObjectPackage workFlowObjectPackage = (WorkFlowObjectPackage) result;
//            List<UserTaskDTO> userTaskList = workFlowObjectPackage.getUserTaskList();
//            if(CollUtil.isNotEmpty(userTaskList)){
//                List<PdmUserDTO> userList = userTaskList.get(0).getUserList();
//                if(CollUtil.isEmpty(userList)){
//                    return result;
//                }
//                PdmUserDTO pdmUserDTO = userList.get(0);
//                //调用服务获取用户的上级组织（即所在部门）
//                List<PrincipalEntity> outParent = this.typlmPrincipalService.getOneOutParentOrg(
//                        new PrincipalEntity(new BigInteger(pdmUserDTO.getOid()), TableTypeConstrant.TY_USER_OTYPE));
//                List<String> list = outParent.stream()
//                        .map(principal -> String.valueOf(principal.getOid()))
//                        .collect(Collectors.toList());
//
//                List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectDeptRoleDOListByDeptId(list);
//                Map<String, DeptRoleDO> roleIdToDeptRoleMap = deptRoleDOS.stream()
//                        .collect(Collectors.toMap(
//                                DeptRoleDO::getRoleId,
//                                Function.identity(),
//                                (existing, replacement) -> existing  // 保留第一个
//                        ));
//                for(UserTaskDTO userTaskDTO : userTaskList){
//                    String name = userTaskDTO.getName();
//                    if ("发起者部门主管".equals(name)) {
//                        DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部门主管");
//                        String userId = deptRoleDO.getUserId();
//                        List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                        userTaskDTO.setUserList(pdmUserDTOS);
//                    } else if ("发起者部长".equals(name)) {
//                        DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部长");
//                        String userId = deptRoleDO.getUserId();
//                        List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                        userTaskDTO.setUserList(pdmUserDTOS);
//                    } else if ("发起者部门分管领导".equals(name)) {
//                        DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部门分管领导");
//                        String userId = deptRoleDO.getUserId();
//                        List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                        userTaskDTO.setUserList(pdmUserDTOS);
//                    }
//                }
//                return result;
//            }
//        }
//        return result;
//    }
//
//
//    //拦截工作流服务中的 getOptionalParticipantUserTaskVO 方法
//    @Around("execution(* com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService.getOptionalParticipantUserTaskVO(java.lang.String, java.math.BigInteger, java.math.BigInteger, java.lang.String, java.math.BigInteger, java.lang.String))")
//    @SneakyThrows
//    public Object getOptionalParticipantUserTaskVO(ProceedingJoinPoint proceedingJoinPoint) {
//        Object result = proceedingJoinPoint.proceed();
//        if(result instanceof OptionalParticipantUserTaskVO){
//            OptionalParticipantUserTaskVO optionalParticipantUserTaskVO = (OptionalParticipantUserTaskVO) result;
//            List<UserTaskDTO> userTaskList = optionalParticipantUserTaskVO.getUserTaskDTOS();
//            List<PdmUserDTO> userList = userTaskList.get(0).getUserList();
//            if(CollUtil.isEmpty(userList)){
//                return result;
//            }
//            PdmUserDTO pdmUserDTO = userList.get(0);
//            //调用服务获取用户的上级组织（即所在部门）
//            List<PrincipalEntity> outParent = this.typlmPrincipalService.getOneOutParentOrg(
//                    new PrincipalEntity(new BigInteger(pdmUserDTO.getOid()), TableTypeConstrant.TY_USER_OTYPE));
//            List<String> list = outParent.stream()
//                    .map(principal -> String.valueOf(principal.getOid()))
//                    .collect(Collectors.toList());
//            List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectDeptRoleDOListByDeptId(list);
//            Map<String, DeptRoleDO> roleIdToDeptRoleMap = deptRoleDOS.stream()
//                    .collect(Collectors.toMap(
//                            DeptRoleDO::getRoleId,
//                            Function.identity(),
//                            (existing, replacement) -> existing  // 保留第一个
//                    ));
//            for(UserTaskDTO userTaskDTO : userTaskList){
//                String name = userTaskDTO.getName();
//                if ("发起者部门主管".equals(name)) {
//                    DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部门主管");
//                    String userId = deptRoleDO.getUserId();
//                    List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                    userTaskDTO.setUserList(pdmUserDTOS);
//                } else if ("发起者部长".equals(name)) {
//                    DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部长");
//                    String userId = deptRoleDO.getUserId();
//                    List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                    userTaskDTO.setUserList(pdmUserDTOS);
//                } else if ("发起者部门分管领导".equals(name)) {
//                    DeptRoleDO deptRoleDO = roleIdToDeptRoleMap.get("部门分管领导");
//                    String userId = deptRoleDO.getUserId();
//                    List<PdmUserDTO> pdmUserDTOS = this.pdmUserService.getUserListByIds(ListUtil.toList(new BigInteger(userId)));
//                    userTaskDTO.setUserList(pdmUserDTOS);
//                }
//            }
//            return result;
//        }
//        return result;
//    }


//    //拦截工作流服务中的 getOptionalParticipantUserTaskVO 方法
//    @Around("execution(* com.hustcad.plm.pdm.workflow.service.TyplmWorkFlowContainerService.getOptionalParticipantUserTaskVO(java.lang.String, java.math.BigInteger, java.math.BigInteger, java.lang.String, java.math.BigInteger, java.lang.String))")
//    @SneakyThrows
//    public Object aroundFlowOperation(ProceedingJoinPoint joinPoint) {
//        // 获取方法参数
//        Object[] args = joinPoint.getArgs();
//        BigInteger workFlowContainerId = (BigInteger) args[1]; // 第二个参数是工作流容器ID
//
//        //从上下文获取当前登录用户
//        OptionalParticipantUserTaskVO participantUserTaskVO = (OptionalParticipantUserTaskVO) joinPoint.proceed();
//        List<UserTaskDTO> userTaskDTOS = participantUserTaskVO.getUserTaskDTOS();
//        UserDO user = TyAccountContext.getUser();
//        BigInteger oid = user.getOid();
//        //构造用户实体用于后续查询组织关系
//        PrincipalEntity principalEntity = new PrincipalEntity(oid, TableTypeConstrant.TY_USER_OTYPE);
//        //调用服务获取用户的上级组织（即所在部门）
//        List<PrincipalEntity> outParent = this.typlmPrincipalService.getOneOutParentOrg(principalEntity);
//        //处理组织关系
//        this.typlmOrgService.dealOrgParentPath(outParent);
//        if (CollUtil.isEmpty(outParent)) {
//            return participantUserTaskVO;
//        }
//        String deptId = "";
//        //遍历上级组织列表
//        for (PrincipalEntity entity : outParent) {
//            if (entity instanceof OrgDO) {
//                OrgDO orgDO = (OrgDO) entity;
//                //找到类型为组织容器的部门作为用户的直接部门
//                String containerotype = orgDO.getContainerotype();
//                if (TableTypeConstrant.TY_ORGCONTAINER_OTYPE.equals(containerotype)) {
//                    deptId = String.valueOf(orgDO.getOid());
//                    break;
//                }
//            }
//        }
//        if (StringUtils.isEmpty(deptId) || StringUtils.isBlank(deptId)) {
//            return participantUserTaskVO;
//        }
//        //根据部门ID查询该部门的所有角色配置信息
//        List<DeptRoleDO> deptRoleDOS = deptRoleMapper.selectByDeptOid(deptId);
//        if (CollUtil.isEmpty(deptRoleDOS)) {
//            return participantUserTaskVO;
//        }
//        boolean hasChanges = false; // 标记是否有更改
//        //遍历所有任务节点
//        for (UserTaskDTO userTaskDTO : userTaskDTOS) {
//            String name = userTaskDTO.getName();
//            if ("发起者部门主管".equals(name)) {
//                if (setPdmUserList(userTaskDTO, deptRoleDOS, "部门主管")) {
//                    hasChanges = true;
//                }
//            } else if ("发起者部长".equals(name)) {
//                if (setPdmUserList(userTaskDTO, deptRoleDOS, "部长")) {
//                    hasChanges = true;
//                }
//            } else if ("发起者部门分管领导".equals(name)) {
//                if (setPdmUserList(userTaskDTO, deptRoleDOS, "部门分管领导")) {
//                    hasChanges = true;
//                }
//            }
//        }
//        // 如果有更改，需要更新工作流容器
//        if (hasChanges) {
//            try {
//                // 获取工作流容器视图
//                WorkFlowContainerView workFlowContainerView = typlmWorkFlowContainerService.getWorkFlowContainerDetailByPrimaryKey(workFlowContainerId);
//                if (workFlowContainerView != null) {
//                    // 更新工作流容器视图中的用户任务列表
//                    workFlowContainerView.setUserTaskList(userTaskDTOS);
//                    // 保存更改到数据库
//                    typlmWorkFlowContainerViewService.update(workFlowContainerView);
//                    log.info("成功更新工作流容器 {} 的任务参与者", workFlowContainerId);
//                }
//            } catch (Exception e) {
//                log.error("更新工作流容器失败: {}", e.getMessage(), e);
//            }
//        }
//
//        //返回结果
//        return participantUserTaskVO;
//    }
//
//    // 设置用户列表的具体实现
//    private boolean setPdmUserList(UserTaskDTO userTaskDTO, List<DeptRoleDO> deptRoleDOS, String roleName) {
//        // 检查必要参数
//        if (userTaskDTO == null) {
//            log.error("userTaskDTO 为 null，无法设置用户列表");
//            return false;
//        }
//
//        if (deptRoleDOS == null) {
//            log.error("deptRoleDOS 为 null，无法设置用户列表");
//            return false;
//        }
//
//        //从部门角色列表中筛选出指定角色的用户编号
//        List<PdmUserDTO> userList = userTaskDTO.getUserList();
//        if (userList == null) {
//            log.warn("userTaskDTO.getUserList() 返回 null，为角色 {} 创建新的用户列表", roleName);
//            userList = new ArrayList<>();
//            userTaskDTO.setUserList(userList);
//        }
//
//        List<String> userNames = deptRoleDOS.stream().filter(
//                        deptRoleDO -> deptRoleDO != null && deptRoleDO.getRoleName() != null && deptRoleDO.getRoleName().equals(roleName))
//                .map(DeptRoleDO::getUserNo)
//                .filter(userNo -> userNo != null) // 过滤掉null的用户编号
//                .collect(
//                        Collectors.toList());
//        if (CollUtil.isNotEmpty(userNames)) {
//            //清空原有用户列表
//            userList.clear();
//            //调用服务获取完整用户信息
//            List<PdmUserDTO> pdmUserDTOS = flowControlService.getPdmUserDTOS(userNames);
//            if (pdmUserDTOS != null && !pdmUserDTOS.isEmpty()) {
//                //将用户信息添加到任务节点中
//                userList.addAll(pdmUserDTOS);
//                log.info("为角色 {} 设置了 {} 个参与者", roleName, pdmUserDTOS.size());
//                return true; // 表示有更改
//            } else {
//                log.warn("flowControlService.getPdmUserDTOS 返回 null 或空列表，角色: {}", roleName);
//            }
//        } else {
//            log.debug("未找到角色 {} 对应的用户编号", roleName);
//        }
//        return false; // 表示没有更改
//    }
}

